{% extends "app/base_site.html" %}

{% block title %} 权限管理 {% endblock title %}

{% block stylesheets %}
  {{ block.super }}
<style>
    .xc_perm-container {
        /*background: #f5f7fa;*/
    }
    
    .xc_modern-card {
        background: white;
        border-radius: 6px;
        padding: 8px 12px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.06);
        margin-bottom: 10px;
    }
    
    .xc_page-header {
        display: flex;
        justify-content: flex-start !important;
        align-items: center;
        padding: 3px 0;
        margin-bottom: 6px;
        min-height: 28px;
        gap: 8px;
        flex-wrap: wrap;
    }
    
    .xc_page-title {
        display: flex;
        align-items: center;
        font-size: 16px;
        font-weight: 400;
        flex-shrink: 0;
    }
    
    .xc_page-title i {
        margin-right: 5px;
        font-size: 14px;
        color: #3b82f6;
    }
    
    .xc_header-right {
        display: flex;
        align-items: center;
        gap: 6px;
    }
    
    .xc_header-actions {
        display: flex;
        align-items: center;
        gap: 5px;
        flex-shrink: 0;
    }
    
    .xc_btn-modern {
        padding: 3px 8px;
        font-size: 11px;
        font-weight: 400;
        border-radius: 3px;
        border: 1px solid #d1d5db;
        background: white;
        color: #374151;
        cursor: pointer;
        transition: all 0.2s;
        display: inline-flex;
        align-items: center;
        gap: 3px;
        white-space: nowrap;
        text-decoration: none;
    }
    
    .xc_btn-modern:hover {
        background: #f9fafb;
        border-color: #3b82f6;
        color: #3b82f6;
    }
    
    .xc_btn-secondary {
        background: white;
        color: #6b7280;
        border: 1px solid #d1d5db;
    }
    
    .xc_btn-secondary:hover {
        background: #f9fafb;
        color: #374151;
        border-color: #9ca3af;
    }

    .xc_table-container {
        overflow-x: auto;
        border-radius: 4px;
        border: 1px solid #e5e7eb;
    }
    
    .xc_table {
        width: 100%;
        border-collapse: collapse;
        font-size: 12px;
    }
    
    .xc_table-header {
        background: #fafafa;
        border-bottom: 1px solid #e5e7eb;
    }
    
    .xc_table-header th {
        padding: 10px 12px;
        text-align: left;
        font-weight: 500;
        color: #374151;
        font-size: 12px;
        white-space: nowrap;
    }
    
    .xc_table-body tr {
        border-bottom: 1px solid #f3f4f6;
        transition: background 0.2s;
    }
    
    .xc_table-body tr:last-child {
        border-bottom: none;
    }
    
    .xc_table-body tr:hover {
        background: #f9fafb;
    }
    
    .xc_table-body td {
        padding: 10px 12px;
        color: #374151;
        vertical-align: middle;
    }
    
    .xc_perm-id {
        display: inline-block;
        padding: 2px 6px;
        background: #f3f4f6;
        border: 1px solid #e5e7eb;
        border-radius: 3px;
        font-size: 11px;
        color: #6b7280;
        font-family: monospace;
    }
    
    .xc_perm-name {
        font-weight: 500;
        color: #374151;
        font-size: 12px;
    }
    
    .xc_perm-codename {
        font-size: 11px;
        color: #9ca3af;
        font-family: monospace;
        margin-top: 2px;
    }
    
    .xc_badge {
        display: inline-block;
        padding: 2px 8px;
        border-radius: 3px;
        font-size: 11px;
        font-weight: 500;
    }
    
    .xc_badge-info {
        background: #e0f2fe;
        color: #0369a1;
    }
    
    .xc_actions {
        display: flex;
        gap: 4px;
    }
    
    .xc_btn-icon {
        padding: 4px 8px;
        font-size: 11px;
        border-radius: 3px;
        border: 1px solid #d1d5db;
        background: white;
        color: #374151;
        cursor: pointer;
        transition: all 0.2s;
        display: inline-flex;
        align-items: center;
        gap: 3px;
        text-decoration: none;
    }
    
    .xc_btn-icon:hover {
        background: #f9fafb;
        border-color: #3b82f6;
        color: #3b82f6;
    }
    
    .xc_btn-icon.delete:hover {
        border-color: #ef4444;
        color: #ef4444;
    }
    
    .xc_pagination {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 6px;
        padding: 12px 0;
        background: white;
        border-radius: 6px;
    }
    
    .xc_page-btn {
        min-width: 30px;
        height: 30px;
        padding: 0 10px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #d1d5db;
        background: white;
        color: #6b7280;
        border-radius: 4px;
        cursor: pointer;
        font-size: 12px;
        transition: all 0.2s;
        text-decoration: none;
        margin: 0 3px;
    }
    
    .xc_page-btn:hover:not(.active) {
        border-color: #3b82f6;
        color: #3b82f6;
    }
    
    .xc_page-btn.active {
        background: #3b82f6;
        color: white;
        border-color: #3b82f6;
    }
    
    .xc_page-info {
        font-size: 11px;
        color: #9ca3af;
        margin: 0 6px;
    }
    
    .xc_empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #9ca3af;
    }
    
    .xc_empty-state i {
        font-size: 48px;
        color: #d1d5db;
        margin-bottom: 12px;
    }
    
    .xc_empty-state p {
        font-size: 12px;
        margin: 0;
    }
    
    .xc_loading-spinner {
        display: inline-block;
        width: 10px;
        height: 10px;
        border: 2px solid #e5e7eb;
        border-top: 2px solid #3b82f6;
        border-radius: 50%;
        animation: xc_spin 1s linear infinite;
        margin-right: 4px;
    }
    
    @keyframes xc_spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    .xc_loading-text {
        color: #6b7280;
        font-size: 11px;
    }
    
    /* 弹窗样式 */
    .xc_modal-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        z-index: 1000;
    }
    
    .xc_modal-overlay.active {
        display: block;
        animation: xc_fadeIn 0.2s ease;
    }
    
    @keyframes xc_fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
    
    .xc_modal-container {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: white;
        border-radius: 8px;
        width: 90%;
        max-width: 650px;
        max-height: 80vh;
        display: flex;
        flex-direction: column;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
        animation: xc_slideIn 0.3s ease;
    }
    
    @keyframes xc_slideIn {
        from {
            transform: translate(-50%, -48%);
            opacity: 0;
        }
        to {
            transform: translate(-50%, -50%);
            opacity: 1;
        }
    }
    
    .xc_modal-header {
        position: relative;
        padding: 14px 18px;
        border-bottom: 1px solid #e5e7eb;
        background: #fafafa;
        border-radius: 8px 8px 0 0;
    }
    
    .xc_modal-title {
        font-size: 16px;
        font-weight: 500;
        color: #374151;
    }
    
    .xc_modal-close {
        position: absolute;
        top: 12px;
        right: 16px;
        width: 30px;
        height: 30px;
        border: none;
        background: white;
        color: #6b7280;
        font-size: 20px;
        line-height: 1;
        cursor: pointer;
        padding: 0;
        border-radius: 4px;
        border: 1px solid #d1d5db;
        transition: all 0.2s;
    }
    
    .xc_modal-close:hover {
        background: #f3f4f6;
        color: #374151;
        border-color: #9ca3af;
    }
    
    .xc_modal-body {
        flex: 1;
        padding: 18px 20px;
        overflow-y: auto;
    }
    
    .xc_form-group {
        margin-bottom: 14px;
    }
    
    .xc_form-label {
        display: block;
        font-size: 13px;
        color: #374151;
        margin-bottom: 6px;
        font-weight: 500;
    }
    
    .xc_form-label .required {
        color: #ef4444;
        margin-left: 2px;
    }
    
    .xc_form-input {
        width: 100%;
        padding: 8px 12px;
        font-size: 13px;
        border: 1px solid #d1d5db;
        border-radius: 4px;
        background: white;
        color: #374151;
        transition: all 0.2s;
        height: 36px;
    }
    
    .xc_form-input:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
    }
    
    .xc_form-input:disabled {
        background: #f9fafb;
        color: #9ca3af;
        cursor: not-allowed;
    }
    
    .xc_form-textarea {
        width: 100%;
        padding: 8px 12px;
        font-size: 13px;
        border: 1px solid #d1d5db;
        border-radius: 4px;
        background: white;
        color: #374151;
        transition: all 0.2s;
        resize: vertical;
        min-height: 80px;
    }
    
    .xc_form-textarea:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
    }
    
    .xc_modal-footer {
        padding: 14px 18px;
        border-top: 1px solid #e5e7eb;
        text-align: right;
        background: #fafafa;
        border-radius: 0 0 8px 8px;
    }
    
    .xc_modal-btn {
        padding: 7px 18px;
        font-size: 13px;
        border-radius: 4px;
        border: 1px solid #d1d5db;
        cursor: pointer;
        margin-left: 10px;
        transition: all 0.2s;
        font-weight: 400;
        background: white;
        color: #374151;
    }
    
    .xc_modal-btn:hover {
        background: #f9fafb;
        border-color: #9ca3af;
    }
    
    .xc_modal-btn-primary {
        background: #3b82f6;
        color: white;
        border-color: #3b82f6;
    }
    
    .xc_modal-btn-primary:hover {
        background: #2563eb;
        border-color: #2563eb;
    }
    
    .xc_detail-item {
        display: flex;
        padding: 8px 0;
        border-bottom: 1px solid #f3f4f6;
        font-size: 13px;
    }
    
    .xc_detail-item:last-child {
        border-bottom: none;
    }
    
    .xc_detail-label {
        width: 100px;
        color: #6b7280;
        font-weight: 500;
        flex-shrink: 0;
    }
    
    .xc_detail-value {
        flex: 1;
        color: #374151;
        word-break: break-all;
    }
    
    .right_col {
        background: #f5f7fa !important;
    }
</style>
{% endblock stylesheets %}

{% block content %}
<div class="right_col" role="main">
    <div class="row">
        <div class="col-md-12">
            <div class="x_panel">
                <div class="xc_perm-container">
                    <div class="xc_modern-card">
                        <div class="xc_page-header">
                            <div class="xc_page-title">
                                <i class="fa fa-key"></i>
                                权限管理
                            </div>
                            <div class="xc_header-actions">
                                <button class="xc_btn-modern xc_btn-secondary" onclick="batchDeletePermissions()" id="batch_delete_perm_btn" style="display: none;">
                                    <i class="fa fa-trash"></i> 批量删除
                                </button>
                                <button class="xc_btn-modern xc_btn-secondary" onclick="openContentTypeListModal()">
                                    内容类型管理
                                </button>
                                <button class="xc_btn-modern xc_btn-secondary" onclick="exportPermissions()">
                                    <i class="fa fa-download"></i> 导出
                                </button>
                                <button class="xc_btn-modern xc_btn-secondary" onclick="openImportModal()">
                                    <i class="fa fa-upload"></i> 导入
                                </button>
                                <button class="xc_btn-modern xc_btn-secondary" onclick="openAddModal()">
                                    <i class="fa fa-plus"></i> 添加权限
                                </button>
                                <button class="xc_btn-modern xc_btn-secondary" onclick="f_reload()">
                                    <i class="fa fa-refresh"></i> 刷新
                                </button>
                            </div>
                            <div>
                                <span id="top_loading" style="display: none;">
                                    <span class="xc_loading-spinner"></span>
                                    <span class="xc_loading-text">加载中...</span>
                                </span>
                                <span id="top_msg">{{top_msg}}</span>
                            </div>
                        </div>

                        <div class="xc_table-container">
                            <table class="xc_table">
                                <thead class="xc_table-header">
                                    <tr>
                                        <th style="width: 40px;">
                                            <input type="checkbox" id="perm_check_all" onchange="toggleAllPermissions(this)" style="cursor: pointer;">
                                        </th>
                                        <th>ID</th>
                                        <th>权限名称</th>
                                        <th>权限路由</th>
                                        <th>内容类型</th>
                                        <th style="text-align: center;">操作</th>
                                    </tr>
                                </thead>
                                <tbody class="xc_table-body">
                                    {%  for d  in data %}
                                    <tr>
                                        <td>
                                            <input type="checkbox" class="perm_checkbox" value="{{ d.id }}" onchange="updateBatchDeleteBtn()" style="cursor: pointer;">
                                        </td>
                                        <td><span class="xc_perm-id">{{ d.id }}</span></td>
                                        <td>
                                            <div class="xc_perm-name">{{ d.name }}</div>
                                            <div class="xc_perm-codename">{{ d.codename }}</div>
                                        </td>
                                        <td><code style="font-size: 10px;">{{ d.codename }}</code></td>
                                        <td><span class="xc_badge xc_badge-info">{{ d.content_type__app_label }}.{{ d.content_type__model }}</span></td>
                                        <td>
                                            <div class="xc_actions">
                                                <button onclick="openViewModal('{{ d.id }}')" class="xc_btn-icon">
                                                    <i class="fa fa-eye"></i> 查看
                                                </button>
                                                <button onclick="openEditModal('{{ d.id }}')" class="xc_btn-icon">
                                                    <i class="fa fa-edit"></i> 编辑
                                                </button>
                                                <button onclick="f_del('{{ d.id }}')" class="xc_btn-icon delete">
                                                    <i class="fa fa-trash"></i> 删除
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                            
                            {% if data|length == 0 %}
                            <div class="xc_empty-state">
                                <i class="fa fa-key"></i>
                                <p>暂无权限数据</p>
                            </div>
                            {% endif %}
                        </div>
                    </div>

                    <div class="xc_pagination">
                        <span class="xc_page-info">共 {{ pageData.page_num }} 页 / {{ pageData.count }} 条</span>
                        {%  for d  in pageData.pageLabels%}
                          {% if d.cur == 1 %}
                            <div class="xc_page-btn active">{{ d.name }}</div>
                          {% else %}
                            <a href="/user/permission?p={{d.page}}&ps={{pageData.page_size}}" class="xc_page-btn">{{ d.name }}</a>
                          {% endif %}
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加/编辑权限弹窗 -->
<div class="xc_modal-overlay" id="permModal">
    <div class="xc_modal-container">
        <div class="xc_modal-header">
            <div class="xc_modal-title" id="modalTitle">添加权限</div>
            <button class="xc_modal-close" onclick="closePermModal()">×</button>
        </div>
        <div class="xc_modal-body">
            <div class="xc_form-group">
                <label class="xc_form-label">权限名称<span class="required">*</span></label>
                <input type="text" id="input_name" class="xc_form-input" placeholder="请输入权限名称">
            </div>
            
            <div class="xc_form-group">
                <label class="xc_form-label">权限路由<span class="required">*</span></label>
                <input type="text" id="input_codename" class="xc_form-input" placeholder="请输入权限路由（如: control_index）">
            </div>
            
            <div class="xc_form-group">
                <label class="xc_form-label">内容类型<span class="required">*</span></label>
                <select id="input_content_type" class="xc_form-input">
                    <option value="">请选择内容类型</option>
                </select>
            </div>
        </div>
        <div class="xc_modal-footer">
            <button class="xc_modal-btn" onclick="closePermModal()">取消</button>
            <button class="xc_modal-btn xc_modal-btn-primary" onclick="submitPermForm()">
                <span id="submit_text">提交</span>
            </button>
        </div>
    </div>
</div>

<!-- 查看权限弹窗 -->
<div class="xc_modal-overlay" id="viewModal">
    <div class="xc_modal-container">
        <div class="xc_modal-header">
            <div class="xc_modal-title">权限详情</div>
            <button class="xc_modal-close" onclick="closeViewModal()">×</button>
        </div>
        <div class="xc_modal-body">
            <div class="xc_detail-item">
                <div class="xc_detail-label">ID：</div>
                <div class="xc_detail-value" id="view_id">-</div>
            </div>
            <div class="xc_detail-item">
                <div class="xc_detail-label">权限名称：</div>
                <div class="xc_detail-value" id="view_name">-</div>
            </div>
            <div class="xc_detail-item">
                <div class="xc_detail-label">权限路由：</div>
                <div class="xc_detail-value" id="view_codename">-</div>
            </div>
            <div class="xc_detail-item">
                <div class="xc_detail-label">内容类型：</div>
                <div class="xc_detail-value" id="view_content_type">-</div>
            </div>
        </div>
        <div class="xc_modal-footer">
            <button class="xc_modal-btn" onclick="closeViewModal()">关闭</button>
        </div>
    </div>
</div>

<!-- 内容类型列表弹窗 -->
<div class="xc_modal-overlay" id="ctListModal">
    <div class="xc_modal-container" style="max-width: 650px; max-height: 85vh;">
        <div class="xc_modal-header">
            <div class="xc_modal-title">内容类型管理</div>
            <button class="xc_modal-close" onclick="closeContentTypeListModal()">×</button>
        </div>
        <div class="xc_modal-body" style="padding: 10px;">
            <!-- 操作按钮 -->
            <div style="margin-bottom: 8px; display: flex; justify-content: space-between; align-items: center;">
                <div style="display: flex; gap: 6px;">
                    <button class="xc_btn-modern xc_btn-secondary" onclick="openCtAddModal()">
                        <i class="fa fa-plus"></i> 添加内容类型
                    </button>
                    <button class="xc_btn-modern xc_btn-secondary" onclick="batchDeleteContentTypes()" id="batch_delete_ct_btn" style="display: none;">
                        <i class="fa fa-trash"></i> 批量删除
                    </button>
                </div>
                <span style="font-size: 11px; color: #6b7280;" id="ct_count_text">加载中...</span>
            </div>
            
            <!-- 内容类型列表 -->
            <div class="xc_table-container" style="max-height: 350px; overflow-y: auto;">
                <table class="xc_table">
                    <thead class="xc_table-header">
                        <tr>
                            <th style="width: 40px;">
                                <input type="checkbox" id="ct_check_all" onchange="toggleAllContentTypes(this)" style="cursor: pointer;">
                            </th>
                            <th>ID</th>
                            <th>应用名称</th>
                            <th>模型名称</th>
                            <th style="text-align: center;">操作</th>
                        </tr>
                    </thead>
                    <tbody class="xc_table-body" id="ct_list_body">
                        <tr>
                            <td colspan="5" style="text-align: center; padding: 30px;">
                                <i class="fa fa-spinner fa-spin"></i> 加载中...
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <!-- 分页 -->
            <div class="xc_pagination" id="ct_pagination" style="padding: 10px 0; display: none;">
                <span class="xc_page-info" id="ct_page_info">共 0 页 / 0 条</span>
                <span id="ct_page_btns"></span>
            </div>
        </div>
        <div class="xc_modal-footer">
            <button class="xc_modal-btn" onclick="closeContentTypeListModal()">关闭</button>
        </div>
    </div>
</div>

<!-- 添加/编辑内容类型弹窗 -->
<div class="xc_modal-overlay" id="ctModal">
    <div class="xc_modal-container">
        <div class="xc_modal-header">
            <div class="xc_modal-title" id="ctModalTitle">添加内容类型</div>
            <button class="xc_modal-close" onclick="closeCtModal()">×</button>
        </div>
        <div class="xc_modal-body">
            <div class="xc_form-group">
                <label class="xc_form-label">应用名称<span class="required">*</span></label>
                <input type="text" id="input_ct_app_label" class="xc_form-input" placeholder="请输入应用名称">
            </div>
            
            <div class="xc_form-group">
                <label class="xc_form-label">模型名称<span class="required">*</span></label>
                <input type="text" id="input_ct_model" class="xc_form-input" placeholder="请输入模型名称">
            </div>
        </div>
        <div class="xc_modal-footer">
            <button class="xc_modal-btn" onclick="closeCtModal()">取消</button>
            <button class="xc_modal-btn xc_modal-btn-primary" onclick="submitCtForm()">
                <span id="ct_submit_text">提交</span>
            </button>
        </div>
    </div>
</div>

<!-- 查看内容类型详情弹窗 -->
<div class="xc_modal-overlay" id="ctViewModal">
    <div class="xc_modal-container">
        <div class="xc_modal-header">
            <div class="xc_modal-title">内容类型详情</div>
            <button class="xc_modal-close" onclick="closeCtViewModal()">×</button>
        </div>
        <div class="xc_modal-body">
            <div class="xc_detail-item">
                <div class="xc_detail-label">ID：</div>
                <div class="xc_detail-value" id="ct_view_id">-</div>
            </div>
            <div class="xc_detail-item">
                <div class="xc_detail-label">应用名称：</div>
                <div class="xc_detail-value" id="ct_view_app_label">-</div>
            </div>
            <div class="xc_detail-item">
                <div class="xc_detail-label">模型名称：</div>
                <div class="xc_detail-value" id="ct_view_model">-</div>
            </div>
        </div>
        <div class="xc_modal-footer">
            <button class="xc_modal-btn" onclick="closeCtViewModal()">关闭</button>
        </div>
    </div>
</div>

<!-- 导入权限数据弹窗 -->
<div class="xc_modal-overlay" id="importModal">
    <div class="xc_modal-container" style="max-width: 500px;">
        <div class="xc_modal-header">
            <div class="xc_modal-title">导入权限数据</div>
            <button class="xc_modal-close" onclick="closeImportModal()">×</button>
        </div>
        <div class="xc_modal-body">
            <div class="xc_form-group">
                <label class="xc_form-label">选择JSON文件<span class="required">*</span></label>
                <input type="file" id="import_file" accept=".json" class="xc_form-input" style="padding: 5px;">
                <div style="margin-top: 8px; font-size: 11px; color: #6b7280;">
                    <i class="fa fa-info-circle"></i> 请选择通过“导出”功能生成的JSON文件
                </div>
            </div>
            <div style="margin-top: 15px; padding: 10px; background: #fef3c7; border-left: 3px solid #f59e0b; font-size: 11px; color: #92400e;">
                <strong>注意事项：</strong>
                <ul style="margin: 5px 0 0 20px; padding: 0;">
                    <li>导入时会智能匹配现有数据</li>
                    <li>相同的权限将被更新，不存在的将被创建</li>
                    <li>导入前请确认数据来源可靠</li>
                </ul>
            </div>
        </div>
        <div class="xc_modal-footer">
            <button class="xc_modal-btn" onclick="closeImportModal()">取消</button>
            <button class="xc_modal-btn xc_modal-btn-primary" onclick="submitImport()">
                <span id="import_submit_text">开始导入</span>
            </button>
        </div>
    </div>
</div>
{% endblock content %}

{% block javascripts %}
  {{ block.super }}
<script>
    let ele_top_loading = $("#top_loading");
    let ele_top_msg = $("#top_msg");
    let currentHandle = 'add'; // 'add' 或 'edit'
    let currentPermId = '';
    let curIsPost = false;

    function f_reload() {
        window.location.reload();
    }
    
    // ============ 添加/编辑弹窗 ============
    function openAddModal() {
        currentHandle = 'add';
        currentPermId = '';
        
        $('#modalTitle').text('添加权限');
        $('#input_name').val('').prop('disabled', false);
        $('#input_codename').val('').prop('disabled', false);
        
        // 加载内容类型列表
        loadContentTypes();
        
        $('#permModal').addClass('active');
    }
    
    function loadContentTypes(selectedId) {
        $.ajax({
            url: '/user/openGetAllContentTypes',
            type: 'get',
            dataType: 'json',
            success: function(res) {
                if(res.code === 1000) {
                    let options = '<option value="">请选择内容类型</option>';
                    res.data.forEach(function(ct) {
                        let selected = selectedId && ct.id == selectedId ? 'selected' : '';
                        options += '<option value="' + ct.id + '" ' + selected + '>' + ct.app_label + '.' + ct.model + '</option>';
                    });
                    $('#input_content_type').html(options);
                } else {
                    myToast2025('加载内容类型失败', 'error');
                }
            },
            error: function() {
                myToast2025('加载内容类型失败', 'error');
            }
        });
    }
    
    function openEditModal(perm_id) {
        currentHandle = 'edit';
        currentPermId = perm_id;
        
        $('#modalTitle').text('编辑权限');
        
        // 加载权限数据
        ele_top_loading.show();
        $.ajax({
            url: '/user/openPermissionInfo',
            type: 'get',
            data: {id: perm_id},
            dataType: 'json',
            success: function(res) {
                ele_top_loading.hide();
                
                if(res.code === 1000 && res.info) {
                    let perm = res.info;
                    
                    $('#input_name').val(perm.name);
                    $('#input_codename').val(perm.codename);
                    
                    // 加载内容类型并选中
                    loadContentTypes(perm.content_type_id);
                    
                    $('#permModal').addClass('active');
                } else {
                    myToast2025(res.msg || '权限不存在', 'error');
                }
            },
            error: function() {
                ele_top_loading.hide();
                myToast2025('加载失败，请稍后重试', 'error');
            }
        });
    }
    
    function closePermModal() {
        $('#permModal').removeClass('active');
        currentPermId = '';
    }
    
    // 点击遮罩层关闭
    $('#permModal').click(function(e) {
        if (e.target === this) {
            closePermModal();
        }
    });
    
    // ESC键关闭
    $(document).keydown(function(e) {
        if (e.keyCode === 27) {
            if($('#permModal').hasClass('active')) {
                closePermModal();
            }
            if($('#viewModal').hasClass('active')) {
                closeViewModal();
            }
            if($('#ctListModal').hasClass('active')) {
                closeContentTypeListModal();
            }
            if($('#ctModal').hasClass('active')) {
                closeCtModal();
            }
            if($('#ctViewModal').hasClass('active')) {
                closeCtViewModal();
            }
        }
    });
    
    function submitPermForm() {
        let name = $('#input_name').val().trim();
        let codename = $('#input_codename').val().trim();
        let content_type_id = $('#input_content_type').val().trim();
        
        // 验证
        if(name === '') {
            myToast2025('请输入权限名称', 'error');
            return false;
        }
        if(codename === '') {
            myToast2025('请输入权限路由', 'error');
            return false;
        }
        if(content_type_id === '') {
            myToast2025('请选择内容类型', 'error');
            return false;
        }
        
        let formData = {
            handle: currentHandle,
            name: name,
            codename: codename,
            content_type_id: content_type_id
        };
        
        if(currentHandle === 'edit') {
            formData.id = currentPermId;
        }
        
        if(curIsPost) {
            myToast2025('正在提交中，请勿重复提交！', 'error', 500);
            return false;
        }
        curIsPost = true;
        
        $('#submit_text').text('提交中...');
        
        let handleUrl = currentHandle === 'add' ? '/user/openPermissionAdd' : '/user/openPermissionEdit';
        
        $.ajax({
            url: handleUrl,
            type: 'post',
            data: formData,
            dataType: 'json',
            error: function() {
                curIsPost = false;
                $('#submit_text').text('提交');
                myToast2025('网络异常，请确定网络正常！', 'error');
            },
            success: function(res) {
                curIsPost = false;
                $('#submit_text').text('提交');
                
                if(res.code === 1000) {
                    myToast2025(res.msg, 'success', 1000);
                    setTimeout(function() {
                        closePermModal();
                        window.location.reload();
                    }, 1000);
                } else {
                    myToast2025(res.msg, 'error');
                }
            }
        });
    }
    
    // ============ 查看详情弹窗 ============
    function openViewModal(perm_id) {
        ele_top_loading.show();
        $.ajax({
            url: '/user/openPermissionInfo',
            type: 'get',
            data: {id: perm_id},
            dataType: 'json',
            success: function(res) {
                ele_top_loading.hide();
                
                if(res.code === 1000 && res.info) {
                    let perm = res.info;
                    
                    $('#view_id').text(perm.id);
                    $('#view_name').text(perm.name);
                    $('#view_codename').text(perm.codename);
                    $('#view_content_type').text(perm.content_type__app_label + '.' + perm.content_type__model);
                    
                    $('#viewModal').addClass('active');
                } else {
                    myToast2025(res.msg || '权限不存在', 'error');
                }
            },
            error: function() {
                ele_top_loading.hide();
                myToast2025('加载失败，请稍后重试', 'error');
            }
        });
    }
    
    function closeViewModal() {
        $('#viewModal').removeClass('active');
    }
    
    $('#viewModal').click(function(e) {
        if (e.target === this) {
            closeViewModal();
        }
    });
    
    // ============ 删除功能 ============
    function f_del(perm_id){
        if(!confirm('确定要删除这个权限吗？删除后将从所有用户中移除！')) {
            return;
        }
        
        ele_top_loading.show();
        $.ajax({
            url: '/user/openPermissionDel',
            type: "post",
            async: true,
            data: {"id":perm_id},
            dataType: "json",
            timeout: 0,
            error: function () {
                ele_top_loading.hide();
                myToast2025("网络异常，请确定网络正常！","error");
            },
            success: function (res) {
                ele_top_loading.hide();
                if(1000 === res.code){
                    myToast2025(res.msg, "success", 1000);
                    setTimeout(function() {
                        window.location.reload();
                    }, 1000);
                }else{
                    myToast2025(res.msg,"error");
                }
            }
        });
    }
    
    // ============ 批量删除权限 ============
    function toggleAllPermissions(checkbox) {
        $('.perm_checkbox').prop('checked', checkbox.checked);
        updateBatchDeleteBtn();
    }
    
    function updateBatchDeleteBtn() {
        let checkedCount = $('.perm_checkbox:checked').length;
        if(checkedCount > 0) {
            $('#batch_delete_perm_btn').show();
        } else {
            $('#batch_delete_perm_btn').hide();
            $('#perm_check_all').prop('checked', false);
        }
    }
    
    function batchDeletePermissions() {
        let checkedIds = [];
        $('.perm_checkbox:checked').each(function() {
            checkedIds.push($(this).val());
        });
        
        if(checkedIds.length === 0) {
            myToast2025('请选择要删除的权限', 'error');
            return;
        }
        
        if(!confirm('确定要删除选中的 ' + checkedIds.length + ' 个权限吗？删除后将从所有用户中移除！')) {
            return;
        }
        
        ele_top_loading.show();
        $.ajax({
            url: '/user/openPermissionBatchDel',
            type: 'post',
            data: {ids: checkedIds.join(',')},
            dataType: 'json',
            error: function() {
                ele_top_loading.hide();
                myToast2025('网络异常！', 'error');
            },
            success: function(res) {
                ele_top_loading.hide();
                if(res.code === 1000) {
                    myToast2025('批量删除成功', 'success', 1000);
                    setTimeout(function() {
                        window.location.reload();
                    }, 1000);
                } else {
                    myToast2025(res.msg, 'error');
                }
            }
        });
    }
    
    // ============ 内容类型管理 ============
    let currentCtHandle = 'add';
    let currentCtId = '';
    let curCtIsPost = false;
    let ctCurrentPage = 1;
    let ctPageSize = 10;
    let ctTotalCount = 0;
    
    // 打开内容类型列表弹窗
    function openContentTypeListModal() {
        $('#ctListModal').addClass('active');
        ctCurrentPage = 1;
        loadContentTypeList();
    }
    
    function closeContentTypeListModal() {
        $('#ctListModal').removeClass('active');
    }
    
    $('#ctListModal').click(function(e) {
        if (e.target === this) {
            closeContentTypeListModal();
        }
    });
    
    // 加载内容类型列表
    function loadContentTypeList() {
        $('#ct_list_body').html('<tr><td colspan="5" style="text-align: center; padding: 30px;"><i class="fa fa-spinner fa-spin"></i> 加载中...</td></tr>');
        
        $.ajax({
            url: '/user/openGetAllContentTypes',
            type: 'get',
            data: {
                page: ctCurrentPage,
                page_size: ctPageSize
            },
            dataType: 'json',
            success: function(res) {
                if(res.code === 1000) {
                    let html = '';
                    ctTotalCount = res.total || res.data.length;
                    
                    if(res.data.length === 0) {
                        html = '<tr><td colspan="5" style="text-align: center; padding: 30px; color: #9ca3af;"><i class="fa fa-database"></i><br/>暂无内容类型数据</td></tr>';
                        $('#ct_pagination').hide();
                    } else {
                        res.data.forEach(function(ct) {
                            html += '<tr>';
                            html += '<td><input type="checkbox" class="ct_checkbox" value="' + ct.id + '" onchange="updateBatchDeleteCtBtn()" style="cursor: pointer;"></td>';
                            html += '<td><span class="xc_perm-id">' + ct.id + '</span></td>';
                            html += '<td><div class="xc_perm-name">' + ct.app_label + '</div></td>';
                            html += '<td><span class="xc_badge xc_badge-info">' + ct.model + '</span></td>';
                            html += '<td><div class="xc_actions">';
                            html += '<button onclick="openCtViewModal(' + ct.id + ')" class="xc_btn-icon"><i class="fa fa-eye"></i> 查看</button>';
                            html += '<button onclick="openCtEditModal(' + ct.id + ')" class="xc_btn-icon"><i class="fa fa-edit"></i> 编辑</button>';
                            html += '<button onclick="deleteContentType(' + ct.id + ')" class="xc_btn-icon delete"><i class="fa fa-trash"></i> 删除</button>';
                            html += '</div></td>';
                            html += '</tr>';
                        });
                        
                        // 显示分页
                        renderCtPagination();
                        $('#ct_pagination').show();
                    }
                    $('#ct_list_body').html(html);
                    $('#ct_count_text').text('共 ' + ctTotalCount + ' 个内容类型');
                    
                    // 重置批量删除按钮状态
                    $('#batch_delete_ct_btn').hide();
                    $('#ct_check_all').prop('checked', false);
                } else {
                    $('#ct_list_body').html('<tr><td colspan="5" style="text-align: center; padding: 30px; color: #ef4444;">' + res.msg + '</td></tr>');
                    $('#ct_pagination').hide();
                }
            },
            error: function() {
                $('#ct_list_body').html('<tr><td colspan="5" style="text-align: center; padding: 30px; color: #ef4444;">加载失败</td></tr>');
                $('#ct_pagination').hide();
            }
        });
    }
    
    // ============ 批量删除内容类型 ============
    function toggleAllContentTypes(checkbox) {
        $('.ct_checkbox').prop('checked', checkbox.checked);
        updateBatchDeleteCtBtn();
    }
    
    function updateBatchDeleteCtBtn() {
        let checkedCount = $('.ct_checkbox:checked').length;
        if(checkedCount > 0) {
            $('#batch_delete_ct_btn').show();
        } else {
            $('#batch_delete_ct_btn').hide();
            $('#ct_check_all').prop('checked', false);
        }
    }
    
    function batchDeleteContentTypes() {
        let checkedIds = [];
        $('.ct_checkbox:checked').each(function() {
            checkedIds.push($(this).val());
        });
        
        if(checkedIds.length === 0) {
            myToast2025('请选择要删除的内容类型', 'error');
            return;
        }
        
        if(!confirm('确定要删除选中的 ' + checkedIds.length + ' 个内容类型吗？删除后关联的权限也将被删除！')) {
            return;
        }
        
        $.ajax({
            url: '/user/openContentTypeBatchDel',
            type: 'post',
            data: {ids: checkedIds.join(',')},
            dataType: 'json',
            error: function() {
                myToast2025('网络异常！', 'error');
            },
            success: function(res) {
                if(res.code === 1000) {
                    myToast2025('批量删除成功', 'success', 1000);
                    loadContentTypeList(); // 重新加载列表
                    loadContentTypes(); // 更新权限表单中的下拉框
                } else {
                    myToast2025(res.msg, 'error');
                }
            }
        });
    }
    
    // 渲染内容类型分页
    function renderCtPagination() {
        let pageNum = Math.ceil(ctTotalCount / ctPageSize);
        if(pageNum <= 1) {
            $('#ct_pagination').hide();
            return;
        }
        
        let html = '';
        
        // 上一页
        if(ctCurrentPage > 1) {
            html += '<a href="javascript:void(0)" onclick="goToCtPage(' + (ctCurrentPage - 1) + ')" class="xc_page-btn">上一页</a>';
        }
        
        // 页码
        let startPage = Math.max(1, ctCurrentPage - 2);
        let endPage = Math.min(pageNum, ctCurrentPage + 2);
        
        if(startPage > 1) {
            html += '<a href="javascript:void(0)" onclick="goToCtPage(1)" class="xc_page-btn">1</a>';
            if(startPage > 2) {
                html += '<span class="xc_page-btn" style="cursor: default; border: none;">…</span>';
            }
        }
        
        for(let i = startPage; i <= endPage; i++) {
            if(i === ctCurrentPage) {
                html += '<div class="xc_page-btn active">' + i + '</div>';
            } else {
                html += '<a href="javascript:void(0)" onclick="goToCtPage(' + i + ')" class="xc_page-btn">' + i + '</a>';
            }
        }
        
        if(endPage < pageNum) {
            if(endPage < pageNum - 1) {
                html += '<span class="xc_page-btn" style="cursor: default; border: none;">…</span>';
            }
            html += '<a href="javascript:void(0)" onclick="goToCtPage(' + pageNum + ')" class="xc_page-btn">' + pageNum + '</a>';
        }
        
        // 下一页
        if(ctCurrentPage < pageNum) {
            html += '<a href="javascript:void(0)" onclick="goToCtPage(' + (ctCurrentPage + 1) + ')" class="xc_page-btn">下一页</a>';
        }
        
        $('#ct_page_btns').html(html);
        $('#ct_page_info').text('共 ' + pageNum + ' 页 / ' + ctTotalCount + ' 条');
    }
    
    // 跳转到指定页
    function goToCtPage(page) {
        ctCurrentPage = page;
        loadContentTypeList();
    }
    
    // 添加内容类型
    function openCtAddModal() {
        currentCtHandle = 'add';
        currentCtId = '';
        
        $('#ctModalTitle').text('添加内容类型');
        $('#input_ct_app_label').val('');
        $('#input_ct_model').val('');
        
        $('#ctModal').addClass('active');
    }
    
    // 编辑内容类型
    function openCtEditModal(ct_id) {
        currentCtHandle = 'edit';
        currentCtId = ct_id;
        
        $('#ctModalTitle').text('编辑内容类型');
        
        $.ajax({
            url: '/user/openContentTypeInfo',
            type: 'get',
            data: {id: ct_id},
            dataType: 'json',
            success: function(res) {
                if(res.code === 1000 && res.info) {
                    $('#input_ct_app_label').val(res.info.app_label);
                    $('#input_ct_model').val(res.info.model);
                    $('#ctModal').addClass('active');
                } else {
                    myToast2025(res.msg || '内容类型不存在', 'error');
                }
            },
            error: function() {
                myToast2025('加载失败', 'error');
            }
        });
    }
    
    function closeCtModal() {
        $('#ctModal').removeClass('active');
    }
    
    $('#ctModal').click(function(e) {
        if (e.target === this) {
            closeCtModal();
        }
    });
    
    // 提交内容类型表单
    function submitCtForm() {
        let app_label = $('#input_ct_app_label').val().trim();
        let model = $('#input_ct_model').val().trim();
        
        if(app_label === '') {
            myToast2025('请输入应用名称', 'error');
            return false;
        }
        if(model === '') {
            myToast2025('请输入模型名称', 'error');
            return false;
        }
        
        let formData = {
            handle: currentCtHandle,
            app_label: app_label,
            model: model
        };
        
        if(currentCtHandle === 'edit') {
            formData.id = currentCtId;
        }
        
        if(curCtIsPost) {
            myToast2025('正在提交中，请勿重复提交！', 'error', 500);
            return false;
        }
        curCtIsPost = true;
        
        $('#ct_submit_text').text('提交中...');
        
        let handleUrl = currentCtHandle === 'add' ? '/user/openContentTypeAdd' : '/user/openContentTypeEdit';
        
        $.ajax({
            url: handleUrl,
            type: 'post',
            data: formData,
            dataType: 'json',
            error: function() {
                curCtIsPost = false;
                $('#ct_submit_text').text('提交');
                myToast2025('网络异常！', 'error');
            },
            success: function(res) {
                curCtIsPost = false;
                $('#ct_submit_text').text('提交');
                
                if(res.code === 1000) {
                    myToast2025(res.msg, 'success', 1000);
                    closeCtModal();
                    loadContentTypeList(); // 重新加载列表
                    loadContentTypes(); // 更新权限表单中的下拉框
                } else {
                    myToast2025(res.msg, 'error');
                }
            }
        });
    }
    
    // 查看内容类型详情
    function openCtViewModal(ct_id) {
        $.ajax({
            url: '/user/openContentTypeInfo',
            type: 'get',
            data: {id: ct_id},
            dataType: 'json',
            success: function(res) {
                if(res.code === 1000 && res.info) {
                    $('#ct_view_id').text(res.info.id);
                    $('#ct_view_app_label').text(res.info.app_label);
                    $('#ct_view_model').text(res.info.model);
                    $('#ctViewModal').addClass('active');
                } else {
                    myToast2025(res.msg || '内容类型不存在', 'error');
                }
            },
            error: function() {
                myToast2025('加载失败', 'error');
            }
        });
    }
    
    function closeCtViewModal() {
        $('#ctViewModal').removeClass('active');
    }
    
    $('#ctViewModal').click(function(e) {
        if (e.target === this) {
            closeCtViewModal();
        }
    });
    
    // 删除内容类型
    function deleteContentType(ct_id) {
        if(!confirm('确定要删除这个内容类型吗？删除后关联的权限也将被删除！')) {
            return;
        }
        
        $.ajax({
            url: '/user/openContentTypeDel',
            type: 'post',
            data: {id: ct_id},
            dataType: 'json',
            error: function() {
                myToast2025('网络异常！', 'error');
            },
            success: function(res) {
                if(res.code === 1000) {
                    myToast2025('删除成功', 'success', 1000);
                    loadContentTypeList(); // 重新加载列表
                    loadContentTypes(); // 更新权限表单中的下拉框
                } else {
                    myToast2025(res.msg, 'error');
                }
            }
        });
    }
    
    // ============ 导出和导入权限数据 ============
    // 导出权限数据
    function exportPermissions() {
        if(!confirm('确认要导出所有权限数据吗？')) {
            return;
        }
        
        ele_top_loading.show();
        ele_top_msg.text('正在导出...');
        
        // 使用window.location直接下载文件
        window.location.href = '/user/exportPermissions';
        
        // 等待一下再隐藏加载提示
        setTimeout(function() {
            ele_top_loading.hide();
            ele_top_msg.text('');
            myToast2025('导出成功，请查看下载文件', 'success');
        }, 1000);
    }
    
    // 打开导入弹窗
    function openImportModal() {
        $('#import_file').val('');
        $('#importModal').addClass('active');
    }
    
    function closeImportModal() {
        $('#importModal').removeClass('active');
        $('#import_file').val('');
    }
    
    $('#importModal').click(function(e) {
        if (e.target === this) {
            closeImportModal();
        }
    });
    
    // 提交导入
    function submitImport() {
        let fileInput = document.getElementById('import_file');
        let file = fileInput.files[0];
        
        if(!file) {
            myToast2025('请选择要导入的JSON文件', 'error');
            return;
        }
        
        if(!file.name.endsWith('.json')) {
            myToast2025('只支持JSON格式文件', 'error');
            return;
        }
        
        if(!confirm('确认要导入该文件的权限数据吗？\n\n相同的权限将被更新，不存在的将被创建。')) {
            return;
        }
        
        let formData = new FormData();
        formData.append('file', file);
        
        $('#import_submit_text').text('导入中...');
        
        $.ajax({
            url: '/user/importPermissions',
            type: 'post',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            error: function() {
                $('#import_submit_text').text('开始导入');
                myToast2025('网络异常！', 'error');
            },
            success: function(res) {
                $('#import_submit_text').text('开始导入');
                
                if(res.code === 1000) {
                    let msg = res.msg;
                    if(res.stats) {
                        msg += '\n\n详细信息：';
                        msg += '\n创建内容类型: ' + res.stats.content_types_created + ' 个';
                        msg += '\n创建权限: ' + res.stats.permissions_created + ' 个';
                        msg += '\n更新权限: ' + res.stats.permissions_updated + ' 个';
                        if(res.stats.permissions_skipped > 0) {
                            msg += '\n跳过重复权限: ' + res.stats.permissions_skipped + ' 个';
                        }
                    }
                    myToast2025('导入完成！', 'success', 2000);
                    closeImportModal();
                    
                    // 显示详细信息
                    setTimeout(function() {
                        alert(msg);
                        // 刷新页面
                        window.location.reload();
                    }, 500);
                } else {
                    myToast2025(res.msg, 'error');
                }
            }
        });
    }
</script>
{% endblock javascripts %}
